package com.android.zweibo.ui;

import java.util.HashMap;
import java.util.Map;

import weibo4android.http.AccessToken;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.Toast;

import com.android.zweibo.bean.Common;
import com.android.zweibo.bean.Task;
import com.android.zweibo.bean.UserInfo;
import com.android.zweibo.logic.MainService;
import com.android.zweibo.logic.UserInfoServices;

/**
 * 获取accessToken
 * @author administrator
 *
 */
public class AccessTokenActivity extends Activity implements IWeiboActivity{
	
	private ProgressDialog proDialog;
	private UserInfoServices userInfoService ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		init();
		//新建任务获取accessToken
		Task task = new Task(Common.ACCESS_TOKEN,null);
		MainService.newTask(task);
		MainService.addActivity(this);
	}

	@Override
	public void init() {
		if(null == proDialog) {
			proDialog = new ProgressDialog(this);
		}
		proDialog.setMessage(getString(R.string.accessToken_Dialog));
		proDialog.show();
		userInfoService = new UserInfoServices(this);
	}

	@Override
	public void refresh(Object... objects) {
		int flag = (Integer) objects[0];
		if(Common.ACCESS_TOKEN == flag) {	
			proDialog.setMessage("正在获取头像");
			AccessToken accessToken = (AccessToken) objects[1];
			
			Toast.makeText(this, accessToken.getUserId() + ":"+accessToken.getScreenName()+":"+accessToken.getToken()+":"+accessToken.getTokenSecret(),Toast.LENGTH_LONG).show();
			
			UserInfo user = new UserInfo( accessToken.getUserId() + "",accessToken.getScreenName(),accessToken.getToken(),
					accessToken.getTokenSecret(),"1");
			if(userInfoService.findUserByID(accessToken.getUserId() + "") == null) {
				userInfoService.insertUserInfo(user);
				Toast.makeText(this, "保存成功 "+ accessToken.getScreenName() + user.getUserId(), Toast.LENGTH_LONG).show();
			}
			else {
				userInfoService.updateUserInfo(user);
				Toast.makeText(this, "已经保存 "+ accessToken.getScreenName() + userInfoService.findUserByID(accessToken.getUserId() + ""), Toast.LENGTH_LONG).show();
			}
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("user", user);
			Task task = new Task(Common.GET_ICON_NAME, param);
			MainService.newTask(task);
			
		}else if(Common.GET_ICON_NAME == flag) {
			proDialog.dismiss();
			UserInfo user = (UserInfo)objects[1];
			BitmapDrawable bitmapDrawable = (BitmapDrawable) user.getUserIcon();
	        userInfoService.updateUserInfo(user.getUserId(), user.getUserName(),bitmapDrawable.getBitmap());
			Intent intent = new Intent(this,LoginActivity.class);
			startActivity(intent);
			this.finish();
		}
		
	}
}
